package com.sandau.rollcall.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestHeader;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;

@Controller
public class AttendanceController {

    private static final String FILE_PATH = "attendance.txt";

    @RequestMapping("/")
    public String showForm() {
        return "index"; // 返回 index.html 页面
    }

    @PostMapping("/submit")
    public String submitName(@RequestParam("name") String name,
                             @RequestHeader(value = "X-FORWARDED-FOR", required = false) String forwardedIp,
                             @RequestHeader(value = "Host", required = false) String hostIp) {

        String clientIp = (forwardedIp != null) ? forwardedIp : hostIp;
        String timestamp = LocalDateTime.now().toString();

        String entry = "Name: " + name + ", IP: " + clientIp + ", Time: " + timestamp;

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_PATH, true))) {
            writer.write(entry);
            writer.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:/"; // 重定向到主页
    }
}